package com.scs.application.modules.msg.sender;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.aliyun.sms.AliyunSmsHandler;
import com.scs.application.core.aliyun.sms.EnableAliyunSms;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.msg.entity.SmsTemplate;
import com.scs.application.modules.msg.model.AliyunSmsMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 */
@Component
@EnableAliyunSms
public class AliyunSmsMessageSender extends SmsMessageSender<AliyunSmsMessage> {

    @Autowired
    private AliyunSmsHandler aliyunSmsHandler;

    @Override
    protected void beforeSend(AliyunSmsMessage msg) {
        super.beforeSend(msg);
    }

    @Override
    protected void doSend(AliyunSmsMessage msg) {
        if (StringUtils.isNotBlank(msg.getTplKey())) {
            SmsTemplate smsTemplate = smsTemplateService.getOne(
                    Wrappers.<SmsTemplate>query()
                            .eq("tpl_key", msg.getTplKey())
                            .eq("platform", "aliyun")
                            .last("limit 1")
            );

            if (smsTemplate == null) {
                throw new BusinessException(String.format("短信发送失败：短信模板[%s]不存在", msg.getTplKey()));
            }
            aliyunSmsHandler.sendSms(msg.getMobiles(), smsTemplate.getPlatformTplCode(), msg.getTplDataMap());
            return;
        }
        aliyunSmsHandler.sendSms(msg.getMobiles(), msg.getPlatformTplCode(), msg.getTplDataMap());
    }

}
